﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Crm.SdkTypeProxy;
using Magnetism.Addons.Common;
using Microsoft.Crm.Sdk;
using System.Net;
using mSpy.UI.Model;
using Microsoft.Crm.SdkTypeProxy.Metadata;

namespace mSpy.UI
{
    internal class Connection
    {
        internal static List<string> GetCrmOrgs(string discourl, string domain, string userName, string password)
        {
            List<string> orgs = new List<string>();

            using (CrmDiscoveryService disco = new CrmDiscoveryService
            {
                Url = discourl,
                Credentials = new NetworkCredential(userName, password, domain)
            })
            {
                RetrieveOrganizationsRequest request = new RetrieveOrganizationsRequest
                {
                    UserId = string.Format(@"{0}\{1}",
                    !string.IsNullOrEmpty(domain) ? domain : CredentialCache.DefaultNetworkCredentials.Domain,
                    !string.IsNullOrEmpty(userName) ? userName : CredentialCache.DefaultNetworkCredentials.UserName),
                    Password = password
                };
                RetrieveOrganizationsResponse response = (RetrieveOrganizationsResponse)disco.Execute(request);

                OrganizationDetail info = null;
                foreach (OrganizationDetail detail in response.OrganizationDetails)
                {
                    orgs.Add(detail.OrganizationName);
                }
            }

            return orgs;
        }

        internal static CrmSdkWrapper GetCrmSdk(string discourl, string organization, string domain, string userName, string password)
        {
            CrmSdkWrapper sdk = new CrmSdkWrapper();
            using (CrmDiscoveryService disco = new CrmDiscoveryService
            {
                Url = discourl,
                Credentials = new NetworkCredential(userName, password, domain)
            })
            {
                RetrieveOrganizationsRequest request = new RetrieveOrganizationsRequest
                {
                    UserId = string.Format(@"{0}\{1}",
                    !string.IsNullOrEmpty(domain) ? domain : CredentialCache.DefaultNetworkCredentials.Domain,
                    !string.IsNullOrEmpty(userName) ? userName : CredentialCache.DefaultNetworkCredentials.UserName),
                    Password = password
                };
                RetrieveOrganizationsResponse response = (RetrieveOrganizationsResponse)disco.Execute(request);

                OrganizationDetail info = null;
                foreach (OrganizationDetail detail in response.OrganizationDetails)
                {
                    if (detail.OrganizationName.Equals(organization, StringComparison.InvariantCultureIgnoreCase))
                    {
                        info = detail;
                        break;
                    }
                }

                if (info != null)
                {
                    RetrieveCrmTicketRequest ticketRequest = new RetrieveCrmTicketRequest
                    {
                        OrganizationName = info.OrganizationName,
                        UserId = request.UserId,
                        Password = request.Password
                    };
                    RetrieveCrmTicketResponse ticketResponse = (RetrieveCrmTicketResponse)disco.Execute(ticketRequest);

                    CrmAuthenticationToken token = new CrmAuthenticationToken
                    {
                        AuthenticationType = 0,
                        OrganizationName = info.OrganizationName,
                        CrmTicket = ticketResponse.CrmTicket
                    };

                    sdk.Sdk = new CrmService
                    {
                        CrmAuthenticationTokenValue = token,
                        Url = info.CrmServiceUrl,
                        Credentials = new NetworkCredential(userName, password, domain)
                    };

                    sdk.Metadata = new MetadataService
                    {
                        CrmAuthenticationTokenValue = token,
                        Url = info.CrmMetadataServiceUrl,
                        Credentials = new NetworkCredential(userName, password, domain)
                    };
                }
            }

            return sdk;
        }
    }
}
